import util from '../common/util.js';
import {client} from '../utils/client.js';

function addToCart(e){
	//console.log(e)
	var _this = this;
	uni.showLoading({
	    title: '加载中...'
	});
	var params = {
		sku_id:e.currentTarget.dataset.idx,
		num:1
	}
	client.post('/api/cart/addcart', params, function(res,message){
		//console.log(res);
		uni.hideLoading();
		util.showToast({title:message});
	},function(res){
		uni.hideLoading();
		if(res){
			util.showToast({title:res});
		}
	},true);
}
function orderPay(type,sub_order_number){
	var _this = this;
	uni.showLoading({
	    title: '加载中...'
	});
	//console.log(type);
	var params = {
		sub_order_number:sub_order_number,
		pay_type:type
	};
	client.post('/api/pay/orderpay', params, function(res,message){
		//console.log(res);
		if(type==1){
			var orderInfo = {  
			    appId: res.appId, 
			    nonceStr: res.nonceStr,
			    package: res.package,
			    signType: res.signType,
			    timeStamp: res.timeStamp, 
			    paySign: res.paySign
			}  
			console.log('微信支付')
			orderPayNow(orderInfo,sub_order_number);
		}else if(type==2){
			util.showToast({title:message});
			//console.log('余额支付')
			uni.redirectTo({
				 url: "/pages/paysuccess/paysuccess?order_mode=2&sub_order_number="+sub_order_number
			})
		}
		uni.hideLoading();
	},function(res){
		uni.hideLoading();
		if(res){
			util.showToast({title:res});
		}
		uni.redirectTo({
			 url: "/pages/orderdetail/orderdetail?sub_order_number="+sub_order_number,
		})
	},true);
}
function orderPayNow(orderInfo,sub_order_number){
	//console.log('调起微信支付')
	uni.requestPayment({
	    provider: 'wxpay',
	    timeStamp: orderInfo.timeStamp,
	    nonceStr: orderInfo.nonceStr,
	    package: orderInfo.package,
	    signType: orderInfo.signType,
	    paySign: orderInfo.paySign,
	    success: function (res) {
	        console.log('success:' + JSON.stringify(res));
			client.post('/api/pay/orderpayquery', {sub_order_number:sub_order_number}, function(res,message){
				uni.redirectTo({
					 url: "/pages/paysuccess/paysuccess?order_mode=2&sub_order_number="+sub_order_number
				})
			},function(res){
				uni.redirectTo({
					 url: "/pages/paysuccess/paysuccess?order_mode=2&sub_order_number="+sub_order_number
				})
			},true);
	    },
	    fail: function (err) {
	        console.log('fail:' + JSON.stringify(err));
			uni.redirectTo({
				 url: "/pages/orderdetail/orderdetail?sub_order_number="+sub_order_number,
			})
	    }
	});
}
function noRepeat(arr){
	let set = new Set(arr);
	let noRepeatArr = [...set];
	return noRepeatArr;
}
module.exports = {
	addToCart: addToCart,
	orderPay:orderPay,
	noRepeat: noRepeat
}
